package com.hyh.admin.controller.es;

import com.alibaba.fastjson.JSON;
import com.hyh.ad.common.core.controller.BaseController;
import com.hyh.ad.common.core.domain.AjaxResult;
import com.hyh.admin.domain.resources.Resources;
import com.hyh.admin.tool.HotSearchUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.*;


/*
 * 搜索管理API
 */
@RestController
@RequestMapping("/api/es")
@Api(tags = "搜索管理")
public class SearchController extends BaseController {
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private HotSearchUtil hotSearchClient;

    /*
     * 搜索框自动补全功能
     */
    @GetMapping("/suggestion")
    @ApiOperation("搜索框自动补全")
    public AjaxResult suggestion(@RequestParam("key") String key) {
        SearchRequest request = new SearchRequest("resources");
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "suggest", // 自动补全的名称 可随意
                SuggestBuilders
                        .completionSuggestion("suggestion")
                        .prefix(key)
                        .skipDuplicates(true)
                        .size(10)
        ));
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Suggest suggest = response.getSuggest();
        List<String> list = new ArrayList<>();
        suggest.getSuggestion("suggest").forEach(suggestion -> {
            suggestion.getOptions().forEach(entry -> {
                list.add(entry.getText().string());
            });
        });
        return AjaxResult.success(list);
    }

    /*
     * 搜索框功能 高亮
     */
    @GetMapping("/search")
    @ApiOperation("搜索框功能 高亮")
    public AjaxResult search(
            @RequestParam("key") String key,
            @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
            @RequestParam(value = "size", required = false, defaultValue = "10") Integer size) {
        // 记录搜索常用关键字
        hotSearchClient.updateSearchResult(key);
        SearchRequest searchRequest = new SearchRequest("resources");
        searchRequest.source()
                .query(QueryBuilders.matchQuery("all", key))
                .from((page - 1) * size)
                .size(size)
                .highlighter(new HighlightBuilder().field("title").field("description").requireFieldMatch(false));

        return getPageResult(searchRequest);
    }



    /*
     * 获取热搜常用关键词
     */
    @GetMapping("/hot")
    @ApiOperation("获取热搜常用关键词")
    public AjaxResult hotSearch() {
        return AjaxResult.success(hotSearchClient.getTopSearchResults());
    }
    //结果的解析方法
    private AjaxResult getPageResult(SearchRequest searchRequest) {
        List<Resources> productComplexes = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        Set<String> seenTitles = new HashSet<>(); // 用于去重的 Set

        try {
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = searchResponse.getHits();
            hits.forEach(hit -> {
                Resources resources = JSON.parseObject(hit.getSourceAsString(), Resources.class);
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();

                // 处理 title 高亮
                if (highlightFields.containsKey("title")) {
                    HighlightField highlightField = highlightFields.get("title");
                    String title = highlightField.getFragments()[0].string();
                    resources.setTitle(title);
                }

                // 按 title 进行去重
                if (!seenTitles.contains(resources.getTitle())) {
                    seenTitles.add(resources.getTitle());
                    productComplexes.add(resources);
                }
            });

            map.put("total", productComplexes.size()); // 修改 total 值
            map.put("data", productComplexes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return AjaxResult.success(map);
    }

}
